package demo.huodongbaoming.config;

import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.List;

/**
 * 负载均衡配置类
 * 配置通用的轮询负载均衡策略
 */
@Configuration
public class LoadBalancerConfiguration {
    
    /**
     * 配置轮询负载均衡策略
     * 使请求在多个服务实例之间轮流分配
     */
    @Bean
    public ReactorLoadBalancer<ServiceInstance> reactorServiceInstanceLoadBalancer(
            Environment environment,
            LoadBalancerClientFactory loadBalancerClientFactory) {
        // 从环境中获取当前正在处理的服务名称
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        // 如果没有获取到服务名称，则使用默认值
        if (name == null) {
            name = "activity-service";
        }
        return new RoundRobinLoadBalancer(
                loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class),
                name);
    }
    
    /**
     * 提供硬编码的服务实例列表
     * 仅在服务发现失败时作为备份使用
     */
    @Bean
    public ServiceInstanceListSupplier staticServiceInstanceListSupplier() {
        return new ServiceInstanceListSupplier() {
            @Override
            public String getServiceId() {
                return "activity-service";
            }

            @Override
            public Flux<List<ServiceInstance>> get() {
                // 创建两个服务实例
                ServiceInstance instance1 = new DefaultServiceInstance(
                        "activity-service-1", "activity-service", "localhost", 8085, false);
                ServiceInstance instance2 = new DefaultServiceInstance(
                        "activity-service-2", "activity-service", "localhost", 8086, false);
                
                return Flux.just(Arrays.asList(instance1, instance2));
            }
        };
    }
} 